# -*- coding: utf-8 -*-

import sys
import os
from .log import log as FP_LOG
from .ModuleLoader import ModuleLoader
import traceback


version = "0.1.0"

Module_Root = os.path.dirname(os.path.split(os.path.realpath(__file__))[0])
UP_DIR = os.path.dirname(Module_Root)
sys.path.append(UP_DIR)
sys.path.append(Module_Root)
sys.path.append("")

ROOT = UP_DIR

_FPLib_log = FP_LOG("FPLib")


class _Global_Storage:
    store = {
        "_Storage_Base": {},
        "var": {},
        "cache": {},
        "conf": {}
    }


class _Storage_Base:
    _key = "_Storage_Base"

    @classmethod
    def set(cls, key, value=""):
        _Global_Storage.store[cls._key][key] = value
        return value

    @classmethod
    def get(cls, key, default=None):
        return _Global_Storage.store[cls._key].get(key, default)

    @classmethod
    def clean(cls, key):
        _Global_Storage.store[cls._key][key] = None

    @classmethod
    def __getattr__(self, name):
        return self.get(name)

    @classmethod
    def __setattr__(self, name, value):
        return self.set(name, value)


class _var(_Storage_Base):
    _key = "var"


class _cache(_Storage_Base):
    _key = "cache"


class _conf(_Storage_Base):
    _key = "conf"


var = _var()
cache = _cache()
conf = _conf()

conf.isdebug = False


def setROOT(newRoot=ROOT):

    global ROOT
    ROOT = os.path.normpath(os.path.join(ROOT, newRoot))


def load(name, path):
    return ModuleLoader.load(name, path)


def lib(name):
    global conf
    module = None
    name = str(name)
    try:
        if name.find('.') > 0:
            mod = name.split('.', 1)
            module = getattr(__import__(mod[0]), mod[1])
        else:
            module = __import__(name)
    except Exception as e:
        if conf.isdebug:
            _FPLib_log.error("\n"+traceback.format_exc()+"\n\n")
        else:
            _FPLib_log.error(e)
        module = None
    return module


def log(name):
    return FP_LOG(name)


def debug(isDebug=True):
    global conf
    if isDebug:
        conf.isdebug = True
    else:
        conf.isdebug = False

    FP_LOG.isdebug(conf.isdebug)
    ModuleLoader.debug(conf.isdebug)


def findError(e=None):
    if conf.isdebug:
        if e:
            _FPLib_log.error(e)
        _FPLib_log.error("\n"+traceback.format_exc()+"\n\n")


def getError(e=None):
    msg = ""
    if e:
        msg += str(e)+" \n";
    msg += traceback.format_exc()
    return msg


def error(e=None):
    return getError(e)
